// create a namespace if not already defined
flyui.namespace("flyui.flybasepub");


/**
 * Create a service object.
 * @class
 * A wrapper for a flybase SPARQL endpoint.
 * @extends flyui.sparql.Service
 * @constructor 
 * @param {String} endpointURL the location of the flybase SPARQL endpoint
 */
flyui.flybasepub.Service = function( endpointURL ) {
	
	/**
	 * @private
	 */
	this._endpoint = endpointURL;
	
};

// extend
flyui.flybasepub.Service.prototype = new flyui.sparql.Service();



flyui.flybasepub.Service.prototype.findPubsByUniqueGeneName = function( fbgn, success, failure, limit ) {
	
	var _context = "flyui.flybasepub.Service.prototype.findPubsByUniqueGeneName";
	try {
        flyui.info("request: "+fbgn, _context);
        flyui.debug("request: "+fbgn, _context);
        flyui.debug("limit: "+limit, _context);
        var chain = flyui.chain(flyui.flybasepub.Service.responseToGene, success);
        var query = flyui.flybasepub.Service._buildQueryForFindPubsByUniqueGeneName(fbgn, limit);
        this.postQuery(query, chain, failure);    
    } catch (error) {
        flyui.debug("wrap and rethrow error to get a stack trace", _context);
        throw new flyui.UnexpectedException(_context, error);
    }   
};





flyui.flybasepub.Service.responseToGene = function( response ) {
    var _context = "flyui.flybasepub.Service.responseToGene";
    try {
        flyui.debug("response status: "+response.status, _context);
        
        flyui.debug("try parsing response text as json", _context);
        flyui.debug("parsing response: "+response.responseText, _context);
        var resultSet = YAHOO.lang.JSON.parse(response.responseText);
        
        flyui.debug("convert result set to an array of publications", _context);
        //TODO
        var publications = flyui.flybasepub.Publication.newInstancesFromSPARQLResults(resultSet);
        return publications;
    } catch (error) {
        flyui.debug("wrap and rethrow error to get a stack trace", _context);
        throw new flyui.UnexpectedException(_context, error);
    }    
};

flyui.flybasepub.Service._buildQueryForFindPubsByUniqueGeneName = function( fbgn, limit ) {
    var _context = "flyui.flybasepub.Service._buildQueryForFindPubsByUniqueGeneName";
    try {

        var prefixes =  "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" +
                        "PREFIX chado: <http://purl.org/net/chado/schema/>\n" +
                        "PREFIX so: <http://purl.org/obo/owl/SO#>\n";

        var body =      "SELECT DISTINCT ?flybaseID ?pub ?title ?miniref ?uniquename WHERE {\n" +
                        "  ?flybaseID \n" +
                        "	 chado:uniquename	\"" + fbgn + "\"^^xsd:string ;\n" +
                        "    a so:SO_0000704 ;\n" +
                        "    chado:organism <http://openflydata.org/id/flybase/organism/Drosophila_melanogaster> ;\n" +
                        "    chado:feature_pub ?pub .\n" +
                        "	 ?pub a chado:Pub ;\n" +
    					"	 	chado:uniquename ?uniquename .\n" +
    					"  OPTIONAL { ?pub chado:title ?title }\n" +
    					"  OPTIONAL { ?pub chado:pyear ?pyear }\n" +
    					"  OPTIONAL { ?pub chado:miniref ?miniref }\n" +
    					"} orderby desc(?pyear) limit "+limit+"\n";
    							    					

        var query = prefixes + body;
    
        return query;
    } catch (error) {
        flyui.debug("wrap and rethrow error to get a stack trace", _context);
        throw new flyui.UnexpectedException(_context, error);
    }    

};


flyui.flybasepub.Publication = function() {
	var that = this ;
	
	this.flybaseID = null;
	
	this.pubID = null;
	
	this.title = "";
	
	this.pyear = "";
	
	this.miniref = "";
};

flyui.flybasepub.Publication.newInstancesFromSPARQLResults = function( resultSet ) {
    var _context = "flyui.flybasepub.Publication.newInstancesFromSPARQLResults";
    try {
		var pool = new flyui.flybasepub.PublicationPool();
				            
        var bindings = resultSet.results.bindings;
        
        for (var i in bindings) {
            var flybaseID = bindings[i].flybaseID.value;
            //flyui.debug("==== the flybaseID " + flybaseID);
            var pubID = bindings[i].pub.value;
            flyui.debug("==== the pubID " + pubID, _context);
            
            if (pubID.search(/unattributed/) == -1){
            
            	publication = pool.get(pubID);
            	publication.flybaseID = flybaseID;         
            	publication.uniquename = bindings[i].uniquename.value;
            	
            	if (bindings[i].title) {
            		publication.title = bindings[i].title.value;
            	}
            
            	if (bindings[i].pyear) {
                	publication.pyear = bindings[i].pyear.value;
            	}
	            if (bindings[i].miniref) {
	                publication.miniref = bindings[i].miniref.value;
	            }
            }
        }
            return pool.toArray();
    } catch (error) {
        flyui.debug("wrap and rethrow error to get a stack trace", _context);
        throw new flyui.UnexpectedException(_context, error);
    }    
};

flyui.flybasepub.PublicationPool = function() {
	
	/**
	 * @private
	 */
	this._pool = new Object();

};

/**
 * Get a publication from the pool, or create a new one if it doesn't exist.
 * @param {String} pubID 
 * @return a flyui.flybasepub.Publication object
 */
flyui.flybasepub.PublicationPool.prototype.get = function( pubID ) {
    var _context = "flyui.flybasepub.PublicationPool.prototype.get";
    try {
        var publication = this._pool[pubID];
        
        if ( typeof publication == "undefined" || !publication ) {
            publication = new flyui.flybasepub.Publication();
            publication.pubID = pubID;
            this._pool[pubID] = publication;   
        }
        
        return publication;
    
    } catch (error) {
        flyui.debug("wrap and rethrow error to get a stack trace", _context);
        throw new flyui.UnexpectedException(_context, error);
    }    	
};

flyui.flybasepub.PublicationPool.prototype.toArray = function() {
    var _context = "flyui.flybasepub.PublicationPool.prototype.toArray";
    try {
        var array = new Array();
        for (var key in this._pool) {
            array[array.length] = this._pool[key];
        }
//        function pubsort(x,y) {
//            if (x.pyear < y.pyear) return 1;
//            else return -1;
//        }
//        array.sort(pubsort);
        return array;
    } catch (error) {
        flyui.debug("wrap and rethrow error to get a stack trace", _context);
        throw new flyui.UnexpectedException(_context, error);
    }    
};
